package com.example.springMVC.service.impl;

import com.example.springMVC.commons.ServiceException;
import com.example.springMVC.dao.UserMapper;
import com.example.springMVC.pojo.User;
import com.example.springMVC.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) throws Exception {
        if ("".equals(user.getUserName()) || "".equals(user.getUserPassword())) {
            throw new ServiceException("输入不能为空");
        }
        User login = userMapper.login(user);
        if (login == null) {
            throw new ServiceException("用户名或密码错误");
        }
        return login;
    }

    @Override
    public PageInfo<User> userList(Integer currentPage, Integer roleId, String userName) {
        Map<String, Object> param = new HashMap<>();
        param.put("roleId", roleId);
        param.put("userName", userName);
        PageHelper.offsetPage((currentPage - 1) * 10, 10, true);
        List<User> userList = userMapper.userList(param);
        PageInfo<User> info = new PageInfo<>(userList);
        return info;
    }

    @Override
    public boolean addUser(User user) throws ServiceException {
        if (StringUtils.isAllBlank(user.getUserCode()) || StringUtils.isAnyBlank(user.getUserPassword()) || StringUtils.isAnyBlank(user.getPhone())) {
            throw new ServiceException("输入不能为空");
        }
        userMapper.addUser(user);
        return true;
    }


    @Override
    public boolean deleteUser(Long userId) {

        return userMapper.deleteUser(userId);
    }

    @Override
    public boolean updateUserById(User user) {
        return userMapper.updateUserById(user);
    }

    @Override
    public User getUserById(long userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public User getUserByCode(String userCode) {
        return userMapper.getUserByCode(userCode);
    }
}
